package com.fau.om.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fau.om.entity.MedicalAdmin;
import com.fau.om.entity.MedicalCallCustomer;
import com.fau.om.entity.MedicalEnterprise;
import com.fau.om.entity.MedicalFinancialOrders;
import com.fau.om.entity.MedicalKeyValue;
import com.fau.om.entity.MedicalOrderReconciliation;
import com.fau.om.entity.MedicalOrders;
import com.fau.om.entity.MedicalOrdersLog;
import com.fau.om.entity.MedicalOrdersNoPass;
import com.fau.om.entity.MedicalOrdersPass;
import com.fau.om.entity.MedicalOrdersProduct;
import com.fau.om.entity.MedicalOrdersStorage;
import com.fau.om.entity.MedicalOrdersWaitDelivery;
import com.fau.om.service.IAuditManagerService;
import com.fau.om.util.Page;
import com.fau.om.util.ParamUtil;
import com.fau.om.util.SystemConfig;

/**
 * @desc 订单审核接口
 * @author suny
 * @datetime 2014年9月15日,上午10:36:10
 */
@Service
@Transactional(readOnly = true)
public class AuditManagerService extends BaseService implements IAuditManagerService {

	@Override
	public Page findPendingOrders(MedicalOrders orders, Map<String, Object> map) {
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrders a where 1=1 and a.hospitalId=? and a.status=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalOrders a where 1=1 and a.hospitalId=? and a.status=? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(orders.getHospitalId());
		objectList.add(SystemConfig.ORDERS_WAIT_AUDIT_TYPE);

		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			countSql.append(" and a.serialNum = ? ");
			statusSql.append(" and a.serialNum = ? ");
			objectList.add(orders.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(orders.getExpressId())) {
			countSql.append(" and a.expressId = ? ");
			statusSql.append(" and a.expressId = ? ");
			objectList.add(orders.getExpressId());
		}
		
		if(StringUtils.isNotBlank(orders.getName())) {
			countSql.append(" and a.name = ? ");
			statusSql.append(" and a.name = ? ");
			objectList.add(orders.getName());
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils .isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])){
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]); 
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		
		List<MedicalOrders> list = new ArrayList<MedicalOrders>();
		for(Object obj : page.getResult()) {
			MedicalOrders bean = (MedicalOrders) obj;
			MedicalAdmin admin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, bean.getCusSerId());
			bean.setCusSerName(admin.getName());
			list.add(bean);
		}
		page.setResult(list);
		return page;
	}

	@Override
	public MedicalOrdersStorage findOrdersById(String id) {
		MedicalOrdersStorage orders = (MedicalOrdersStorage) this.iBaseDao.getObject(MedicalOrdersStorage.class, id);
		MedicalCallCustomer customer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, orders.getCustomerId());
		orders.setMoney(customer.getMoney());
		orders.setRedEnvelopes(customer.getRedEnvelopes());
		orders.setIntegral(customer.getIntegral());
		return orders;
	}

	@Override
	public String findBackCount(String eid) {
		MedicalKeyValue keyVal = (MedicalKeyValue) this.iBaseDao.getObjectByHql("from MedicalKeyValue a where a.typeName=? and a.hospitalId=? ", SystemConfig.SET_BACK_COUNT_TYPE, eid);
		return keyVal.getKeyValue();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalOrdersProduct> findProductByOid(String oid) {
		return this.iBaseDao.getBySql("from MedicalOrdersProduct a where a.ordersId=? ", null, oid);
	}
	
	@Override
	public MedicalCallCustomer findCustomerById(String id) {
		return (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, id);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void auditOrdersPass(MedicalAdmin admin, MedicalOrders orders) {
		MedicalOrders bean = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, orders.getId());
		MedicalEnterprise enterprise = (MedicalEnterprise) this.iBaseDao.getObject(MedicalEnterprise.class, admin.getEnterpriseId());
		MedicalOrdersPass ordersPass = new MedicalOrdersPass();
		BeanUtils.copyProperties(bean, ordersPass);
		ordersPass.setMediaId(bean.getMedia().getId());
		// 核单部直接审核订单，存入审核人员id,所在中心id，组id
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			if(StringUtils.isBlank(bean.getCenterId())) {
				ordersPass.setCenterId(admin.getGroup().getPlatform().getId());
			} else {}
			
			if(StringUtils.isBlank(bean.getGroupId())) {
				ordersPass.setGroupId(admin.getGroup().getId());
			} else {}
		}
		
		if(StringUtils.isBlank(bean.getCheckUserId())) {
			ordersPass.setCheckUserId(admin.getId());
		} else {}
		ordersPass.setCheckTime(new Date());
		this.iBaseDao.addObject(ordersPass);
		MedicalOrdersStorage ordersStorage = (MedicalOrdersStorage) this.iBaseDao.getObject(MedicalOrdersStorage.class, orders.getId());
		ordersStorage.setOrdersStatus(SystemConfig.ORDERS_AUDIT_PASS_TYPE);
		ordersStorage.setCheckTime(new Date());
		ordersStorage.setCenterId(ordersPass.getCenterId());
		ordersStorage.setGroupId(ordersPass.getGroupId());
		ordersStorage.setCheckUserId(ordersPass.getCheckUserId());
		// 线下汇款，移交财务对账
		if(SystemConfig.ORDERS_DOWNLINE_PAY_TYPE.equals(bean.getPayType())) {
			if(SystemConfig.FINANCIAL_HAS_RECONCILIATION.equals(enterprise.getNeedStatus()) || SystemConfig.FINANCIAL_RECON_BACK_SECTION.equals(enterprise.getNeedStatus())) {
				MedicalFinancialOrders financialOrders = new MedicalFinancialOrders();
				BeanUtils.copyProperties(ordersPass, financialOrders);
				this.iBaseDao.addObject(financialOrders);
				ordersStorage.setFinancialStatus(SystemConfig.BE_RECONCILED);
			} else if(SystemConfig.FINANCIAL_HAS_BACK_SECTION.equals(enterprise.getNeedStatus())) {
				MedicalOrderReconciliation orderReconciliation = new MedicalOrderReconciliation();
				orderReconciliation.setClaimStatus(SystemConfig.UN_CLAIMED);
				BeanUtils.copyProperties(ordersPass, orderReconciliation);
				this.iBaseDao.addObject(orderReconciliation);
			} else {		// 无对账、无回款，发货人员线下查看钱到账，发货。
				MedicalOrdersWaitDelivery ordersWaitDelivery = new MedicalOrdersWaitDelivery();
				BeanUtils.copyProperties(ordersPass, ordersWaitDelivery);
				ordersWaitDelivery.setCheckTime(new Date());
				this.iBaseDao.addObject(ordersWaitDelivery);
				ordersStorage.setWarehouseStatus(SystemConfig.ORDERS_WAIT_DELIVERY_TYPE);
			}
		} else {		// 快递代收移交仓储发货
			MedicalOrdersWaitDelivery ordersWaitDelivery = new MedicalOrdersWaitDelivery();
			BeanUtils.copyProperties(ordersPass, ordersWaitDelivery);
			ordersWaitDelivery.setCheckTime(new Date());
			this.iBaseDao.addObject(ordersWaitDelivery);
			ordersStorage.setWarehouseStatus(SystemConfig.ORDERS_WAIT_DELIVERY_TYPE);
		}
		this.iBaseDao.deleteObject(bean);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void auditOrdersNoPass(MedicalAdmin admin, MedicalOrders orders) {
		MedicalOrders bean = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, orders.getId());
		MedicalOrdersNoPass ordersNoPass = new MedicalOrdersNoPass();
		BeanUtils.copyProperties(bean, ordersNoPass);
		ordersNoPass.setReasonType(orders.getReasonType());
		ordersNoPass.setReasonRemark(orders.getReasonRemark());
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			// 核单部直接审核订单，存入审核人员id,所在中心id，组id
			if(StringUtils.isBlank(bean.getCenterId())) {
				ordersNoPass.setCenterId(admin.getGroup().getPlatform().getId());
			} else {}
			
			if(StringUtils.isBlank(bean.getGroupId())) {
				ordersNoPass.setGroupId(admin.getGroup().getId());
			} else {}
		}
		
		if(StringUtils.isBlank(bean.getCheckUserId())) {
			ordersNoPass.setCheckUserId(admin.getId());
		} else {}
		ordersNoPass.setCheckTime(new Date());
		this.iBaseDao.addObject(ordersNoPass);
		MedicalOrdersStorage ordersStorage = (MedicalOrdersStorage) this.iBaseDao.getObject(MedicalOrdersStorage.class, orders.getId());
		ordersStorage.setReasonType(orders.getReasonType());
		ordersStorage.setReasonRemark(orders.getReasonRemark());
		ordersStorage.setOrdersStatus(SystemConfig.ORDERS_AUDIT_NOPASS_TYPE);
		this.iBaseDao.deleteObject(bean);
		
		MedicalCallCustomer customer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, ordersStorage.getCustomerId());
		customer.setMoney(customer.getMoney().add(ordersStorage.getUseMoney()));			// 加回余额
		customer.setIntegral(customer.getIntegral() + ordersStorage.getUsePoints());		// 积分
		customer.setRedEnvelopes(customer.getRedEnvelopes() + ordersStorage.getUseRed() - ordersStorage.getRed());	// 红包
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void auditOrdersInvalid(MedicalOrders orders, MedicalAdmin admin) {
		MedicalOrders bean = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, orders.getId());
		MedicalOrdersStorage ordersStorage = (MedicalOrdersStorage) this.iBaseDao.getObject(MedicalOrdersStorage.class, orders.getId());
		// 核单部直接审核订单，存入审核人员id,所在中心id，组id
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			if(StringUtils.isBlank(bean.getCenterId())) {
				ordersStorage.setCenterId(admin.getGroup().getPlatform().getId());
			} else {}
			
			if(StringUtils.isBlank(bean.getGroupId())) {
				ordersStorage.setGroupId(admin.getGroup().getId());
			} else {}
		}
		if(StringUtils.isBlank(bean.getCheckUserId())) {
			ordersStorage.setCheckUserId(admin.getId());
		} else {}
		ordersStorage.setCheckTime(new Date());
		ordersStorage.setOrdersStatus(SystemConfig.ORDERS_AUDIT_INVALID_TYPE);
		
		MedicalCallCustomer customer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, ordersStorage.getCustomerId());
		customer.setMoney(customer.getMoney().add(ordersStorage.getUseMoney()));			// 加回余额
		customer.setIntegral(customer.getIntegral() + ordersStorage.getUsePoints());		// 积分
		customer.setRedEnvelopes(customer.getRedEnvelopes() + ordersStorage.getUseRed() - ordersStorage.getRed());	// 红包
		
		this.iBaseDao.deleteObject(bean);
	}
	
	@Override
	public Page findPlatformPendingOrders(MedicalOrders orders, Map<String, Object> map, MedicalAdmin admin) {
		StringBuilder statusSql = new StringBuilder("from MedicalOrders a where 1=1 and a.hospitalId=? ");
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrders a where 1=1 and a.hospitalId=? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(admin.getEnterpriseId());
		
		if(SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			statusSql.append(" and a.allocateGrade=? ");
			countSql.append(" and a.allocateGrade=? ");
			objectList.add(SystemConfig.ORDERS_GRADE_CENTER);
		} else {
			statusSql.append(" and a.centerId=? ");
			countSql.append(" and a.centerId=? ");
			objectList.add(orders.getCenterId());
		}
		
		if(StringUtils.isNotBlank(orders.getSerialNum())){
			countSql.append("and a.serialNum=? ");
			statusSql.append("and a.serialNum=? ");
			objectList.add(orders.getSerialNum());
		}
		if(StringUtils.isNotBlank(orders.getName())){
			countSql.append("and a.name=? ");
			statusSql.append("and a.name=? ");
			objectList.add(orders.getName());
		}
		if(null != orders.getStartTime()){
			countSql.append("and a.createTime >= ? ");
			statusSql.append("and a.createTime >= ? ");
			objectList.add(orders.getCreateTime());
		}
		if(null != orders.getEndTime()){
			countSql.append("and a.createTime <= ? ");
			statusSql.append("and a.createTime <= ? ");
			objectList.add(orders.getCreateTime());
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils .isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])){
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]); 
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalOrders> ordersList = new ArrayList<MedicalOrders>();
		for(Object obj : page.getResult()){
			MedicalOrders bean = (MedicalOrders) obj;
			MedicalAdmin user = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, bean.getCusSerId());
			bean.setCusSerName(user.getName());
			ordersList.add(bean);
		}
		page.setResult(ordersList);
		return page;
	}

	@Override
	public Page findGroupPendingOrders(MedicalOrders orders, Map<String, Object> map, MedicalAdmin admin) {
		StringBuilder statusSql = new StringBuilder("from MedicalOrders a where 1=1 and a.hospitalId=? ");
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrders a where 1=1 and a.hospitalId=? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(admin.getEnterpriseId());
		if(SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			statusSql.append("and a.allocateGrade=? ");
			countSql.append("and a.allocateGrade=? ");
			objectList.add(SystemConfig.ORDERS_GRADE_GROUP);
		} else {
			statusSql.append(" and a.groupId =? ");
			countSql.append(" and a.groupId =? ");
			objectList.add(admin.getGroup().getId());
		}
		
		if(StringUtils.isNotBlank(orders.getSerialNum())){
			countSql.append("and a.serialNum=? ");
			statusSql.append("and a.serialNum=? ");
			objectList.add(orders.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(orders.getName())){
			countSql.append("and a.name=? ");
			statusSql.append("and a.name=? ");
			objectList.add(orders.getName());
		}
		
		if(null !=orders.getStartTime()){
			countSql.append("and a.createTime >= ? ");
			statusSql.append("and a.createTime >= ? ");
			objectList.add(orders.getCreateTime());
		}
		
		if(null !=orders.getEndTime()){
			countSql.append("and a.createTime <= ? ");
			statusSql.append("and a.createTime <= ? ");
			objectList.add(orders.getCreateTime());
		}

		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils .isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])){
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]); 
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalOrders> ordersList = new ArrayList<MedicalOrders>();
		for(Object obj : page.getResult()){
			orders = (MedicalOrders)obj;
			orders = (MedicalOrders)obj;
			MedicalAdmin user = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, orders.getCusSerId());
			orders.setCusSerName(user.getName());
			
			ordersList.add(orders);
		}
		page.setResult(ordersList);
		return page;
	}

	@Override
	public Page findMyPendingOrders(MedicalOrders orders, Map<String, Object> map) {
		StringBuilder statusSql = new StringBuilder("from MedicalOrders a where 1=1 and a.checkUserId=? ");
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrders a where 1=1 and a.checkUserId=? ");
		
		List<Object> objectList = new ArrayList<Object>();
		
		objectList.add(orders.getCheckUserId());
		
		if(StringUtils.isNotBlank(orders.getSerialNum())){
			countSql.append("and a.serialNum=? ");
			statusSql.append("and a.serialNum=? ");
			objectList.add(orders.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(orders.getName())){
			countSql.append("and a.name=? ");
			statusSql.append("and a.name=? ");
			objectList.add(orders.getName());
		}
		
		if(null !=orders.getStartTime()){
			countSql.append("and a.createTime >= ? ");
			statusSql.append("and a.createTime >= ? ");
			objectList.add(orders.getCreateTime());
		}
		
		if(null !=orders.getEndTime()){
			countSql.append("and a.createTime <= ? ");
			statusSql.append("and a.createTime <= ? ");
			objectList.add(orders.getCreateTime());
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils .isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])){
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]); 
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalOrders> ordersList = new ArrayList<MedicalOrders>();
		for(Object obj : page.getResult()){
			orders = (MedicalOrders)obj;
			MedicalAdmin admin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, orders.getCusSerId());
			orders.setCusSerName(admin.getName());
			
			ordersList.add(orders);
		}
		page.setResult(ordersList);
		return page;
	}

	@Override
	public Workbook exportOrdersCurrent(String ids) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_WAITAUDIT);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] ordersIds =  ids.split(",");
			for(int j=0;j<ordersIds.length;j++){
				// 获得记录
				MedicalOrders order = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, ordersIds[j]);
				i++;
				Row currentRow = sheet.createRow(i);
				currentRow.createCell(0).setCellValue(i);
				if(null != order){
					currentRow.createCell(1).setCellValue(order.getSerialNum());
					currentRow.createCell(2).setCellValue(order.getCusSerName());
					currentRow.createCell(3).setCellValue(order.getCreateTime());
					currentRow.createCell(4).setCellValue(order.getName());
					currentRow.createCell(5).setCellValue(order.getProvince().getpName());
					currentRow.createCell(6).setCellValue(order.getCity().getcName());
					currentRow.createCell(7).setCellValue(order.getDistrict().getdName());
					currentRow.createCell(8).setCellValue(order.getAddress());
					if(null != order.getPayment()) {
						currentRow.createCell(9).setCellValue(order.getPayment().toString());
					}
					if(null != order.getFreight()) {
						currentRow.createCell(10).setCellValue(order.getFreight().toString());
					}
					currentRow.createCell(11).setCellValue(order.getMedia().getName());
				}
			}
		}
		return workbook;
	}

	@SuppressWarnings("all")
	@Override
	public Workbook exportOrdersAll(MedicalOrders orders) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_WAITAUDIT);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId = ? and m.status=? ");
		List<MedicalOrders> ordersList = this.iBaseDao.getBySql(hql.toString(), null, orders.getHospitalId(), SystemConfig.ORDERS_WAIT_AUDIT_TYPE);
		
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCusSerName());
				currentRow.createCell(3).setCellValue(order.getCreateTime());
				currentRow.createCell(4).setCellValue(order.getName());
				currentRow.createCell(5).setCellValue(order.getProvince().getpName());
				currentRow.createCell(6).setCellValue(order.getCity().getcName());
				currentRow.createCell(7).setCellValue(order.getDistrict().getdName());
				currentRow.createCell(8).setCellValue(order.getAddress());
				if(null != order.getPayment()) {
					currentRow.createCell(9).setCellValue(order.getPayment().toString());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(10).setCellValue(order.getFreight().toString());
				}
				currentRow.createCell(11).setCellValue(order.getMedia().getName());
			}
		}
		return workbook;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportCenterOrdersAll(MedicalOrders orders, MedicalAdmin admin) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_WAITAUDIT);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		List<MedicalOrders> ordersList = new ArrayList<MedicalOrders>();
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId = ? ");
		objectList.add(orders.getHospitalId());
		
		if(SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			hql.append("and m.allocateGrade=?");
			objectList.add(SystemConfig.ORDERS_GRADE_CENTER);
		} else {
			hql.append("and m.centerId=? ");
			objectList.add(admin.getGroup().getPlatform().getId());
		}
		ordersList = this.iBaseDao.getBySql(hql.toString(), null, objectList.toArray());
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCusSerName());
				currentRow.createCell(3).setCellValue(order.getCreateTime());
				currentRow.createCell(4).setCellValue(order.getName());
				currentRow.createCell(5).setCellValue(order.getProvince().getpName());
				currentRow.createCell(6).setCellValue(order.getCity().getcName());
				currentRow.createCell(7).setCellValue(order.getDistrict().getdName());
				currentRow.createCell(8).setCellValue(order.getAddress());
				if(null != order.getPayment()) {
					currentRow.createCell(9).setCellValue(order.getPayment().toString());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(10).setCellValue(order.getFreight().toString());
				}
				currentRow.createCell(11).setCellValue(order.getMedia().getName());
			}
		}
		return workbook;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportGroupOrdersAll(MedicalOrders orders, MedicalAdmin admin) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_WAITAUDIT);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		List<MedicalOrders> ordersList = new ArrayList<MedicalOrders>();
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId = ? ");
		objectList.add(orders.getHospitalId());
		
		if(SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			hql.append("and m.allocateGrade=?");
			objectList.add(SystemConfig.ORDERS_GRADE_GROUP);
		} else {
			hql.append("and m.groupId=? ");
			objectList.add(admin.getGroup().getId());
		}
		ordersList = this.iBaseDao.getBySql(hql.toString(), null, objectList.toArray());
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCusSerName());
				currentRow.createCell(3).setCellValue(order.getCreateTime());
				currentRow.createCell(4).setCellValue(order.getName());
				currentRow.createCell(5).setCellValue(order.getProvince().getpName());
				currentRow.createCell(6).setCellValue(order.getCity().getcName());
				currentRow.createCell(7).setCellValue(order.getDistrict().getdName());
				currentRow.createCell(8).setCellValue(order.getAddress());
				if(null != order.getPayment()) {
					currentRow.createCell(9).setCellValue(order.getPayment().toString());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(10).setCellValue(order.getFreight().toString());
				}
				currentRow.createCell(11).setCellValue(order.getMedia().getName());
			}
		}
		return workbook;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportMyOrdersAll(MedicalOrders orders, MedicalAdmin admin) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_WAITAUDIT);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		List<MedicalOrders> ordersList = new ArrayList<MedicalOrders>();
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId=? and a.checkUserId=?");
		objectList.add(orders.getHospitalId());
		objectList.add(admin.getId());
		
		ordersList = this.iBaseDao.getBySql(hql.toString(), null, objectList.toArray());
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCusSerName());
				currentRow.createCell(3).setCellValue(order.getCreateTime());
				currentRow.createCell(4).setCellValue(order.getName());
				currentRow.createCell(5).setCellValue(order.getProvince().getpName());
				currentRow.createCell(6).setCellValue(order.getCity().getcName());
				currentRow.createCell(7).setCellValue(order.getDistrict().getdName());
				currentRow.createCell(8).setCellValue(order.getAddress());
				if(null != order.getPayment()) {
					currentRow.createCell(9).setCellValue(order.getPayment().toString());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(10).setCellValue(order.getFreight().toString());
				}
				currentRow.createCell(11).setCellValue(order.getMedia().getName());
			}
		}
		return workbook;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalOrdersLog> findOrdersLogByNo(String orderNo) {
		return this.iBaseDao.getBySql("from MedicalOrdersLog m where m.orderNo = ? order by m.createTime desc ", null, orderNo);
	}

	@Override
	public String validOrders(String ordersId) {
		MedicalOrders orders = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, ordersId);
		StringBuilder status = new StringBuilder("");
		if(null == orders) {
			status.append("0");			// 已被审核
		} else {
			if(SystemConfig.ORDERS_GRADE_USER.equals(orders.getAllocateGrade())) {
				status.append("1");		// 在话务员处，回收后再审核
			}
		}
		return status.toString();
	}
	
}
